/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
typedef struct ListNode ListNode;

ListNode* detectCycle(ListNode* head)
{
    if (!head || !head->next)
        return NULL;
    ListNode* front, * back;
    front = back = head;
    bool flag = false;

    while (front && front->next)
    {
        if (front == back && flag)
            break;
        front = front->next->next;
        back = back->next;
        flag = true;
    }

    if (!front || !front->next)
        return NULL;

    back = head;

    while (front != back)
    {
        front = front->next;
        back = back->next;
    }

    return front;
}